package com.rabbiter.oes.config;

import com.rabbiter.oes.entity.QuestionDTO;
import org.apache.poi.ss.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {
    // ExcelUtil.java
    public static List<QuestionDTO> parseQuestionExcel(InputStream is) throws IOException {
        List<QuestionDTO> list = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(is);
        Sheet sheet = workbook.getSheetAt(0); // 默认读第一个 sheet

        // 从第2行开始（第1行是表头）
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            QuestionDTO q = new QuestionDTO();

            q.setType(getCellValue(row.getCell(0)));     // 题目类型
            q.setQuestion(getCellValue(row.getCell(1)));  // 题干
            q.setOptionA(getCellValue(row.getCell(2)));
            q.setOptionB(getCellValue(row.getCell(3)));
            q.setOptionC(getCellValue(row.getCell(4)));
            q.setOptionD(getCellValue(row.getCell(5)));
            q.setAnswer(getCellValue(row.getCell(6)));   // 正确答案
            try {
                String scoreStr = getCellValue(row.getCell(7));
                q.setScore(scoreStr.isEmpty() ? 0 : Integer.parseInt(scoreStr));
            } catch (NumberFormatException e) {
                q.setScore(0); // 解析失败设为0
            }
            q.setDifficulty(getCellValue(row.getCell(8))); // 难度

            list.add(q);
        }

        return list;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return "";
        // 强制转为字符串类型，避免数字、日期等格式问题
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }
}
